package com.wy.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})//表示拦截被这两个注解标注的类
@RestController
public class GlobalExceptionHandler {
    /**
     * 捕捉重复用户的异常情况
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exception(SQLIntegrityConstraintViolationException ex) {
        log.info(ex.getMessage());
        //如果异常中包含对应的Duplicate key异常信息,那么就将该账户名获取
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "账号已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * 自定义CustomException异常处理方法
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exception(CustomException ex) {
        log.info(ex.getMessage());

        return R.error(ex.getMessage());
    }
}
